package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * Date:2024/9/21 11:47
 * Author:ybc
 * Description:
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //通过反射的Class对象获取枚举类型中所有的枚举项
                T[] constants = targetType.getEnumConstants();
                for (T t : constants) {
                    if(t.getCode().equals(Integer.valueOf(source))){
                        return t;
                    }
                }
                throw new IllegalArgumentException("code非法");
            }
        };
    }
}
